package com.feizhi.inventory.fragment.inventory;

import static android.content.Context.INPUT_METHOD_SERVICE;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.aserbao.aserbaosandroid.functions.database.greenDao.db.DaoSession;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDao;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDetailsDao;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.myDataDao;
import com.feizhi.inventory.MainActivity;
import com.feizhi.inventory.R;
import com.feizhi.inventory.bean.InventoryBean;
import com.feizhi.inventory.database.Task;
import com.feizhi.inventory.database.dbApp;
import com.feizhi.inventory.database.myData;
import com.feizhi.inventory.databinding.FragmentInventoryPanBinding;
import com.feizhi.inventory.util.ThreadPool;
import com.feizhi.inventory.util.Util;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;


/**
 * 盘点计划
 */
public class InventoryPanFragment extends Fragment implements View.OnClickListener, TextView.OnEditorActionListener {
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    List<Task> list;
    List<myData> listData;
    TaskMyAdapter adapter;
    String fileName, filePath;


    List<Task> taskList = new ArrayList<>();
    private static final int OPEN_FILE_REQUEST_CODE = -1;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.MOUNT_UNMOUNT_FILESYSTEMS"};
    private MainActivity mActivity;

    List<myData> dataList = new ArrayList<>();

    TaskDao taskDao;

    private TaskDetailsDao taskDetailsDao;
    myDataDao dataDao;

    SharedPreferences sharedPreferences;
    private FragmentInventoryPanBinding mBinding;

    private Util util = new Util();
    private ImageView titleAdd;
    private TextView titleTextBack, titleText;
    private ImageView titleBack;
    private List<InventoryBean> data;
    private ImageView add;
    private InventoryAdapter adapter1;
    private List<Map<String, String>> datalist;
    private String count;
    DaoSession updaoSession;
    private ProgressDialog progressDialog;

    public InventoryPanFragment() {
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (MainActivity) getActivity();

        updaoSession = ((dbApp) mActivity.getApplication()).getDaoSession();


        /**
         * 动态去获取权限
         * 暂时放在这里，正常来说要操作读取的时候才需要调用的
         *
         * */
        getPermission();


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mBinding = FragmentInventoryPanBinding.inflate(inflater);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        setOnClickListener();
    }

    /*
     * 处理是点击事件
     * */
    private void setOnClickListener() {


//        titleTextBack.setVisibility(View.VISIBLE);

        titleBack.setOnClickListener(this);
        titleAdd.setOnClickListener(this);
        List<String> name = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {

            name.add(list.get(i).getTable_name());

        }
//        list = taskDao.loadAll();
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(mActivity, android.R.layout.simple_dropdown_item_1line, name);
        mBinding.edtSearch.setAdapter(arrayAdapter);
        mBinding.edtSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBinding.edtSearch.showDropDown();

                // 请求输入框获取焦点，弹出软键盘
                mBinding.edtSearch.requestFocus();
                mBinding.edtSearch.requestFocusFromTouch();
                InputMethodManager inputMethodManager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(mBinding.edtSearch, InputMethodManager.SHOW_IMPLICIT);
            }
        });
        mBinding.edtSearch.setOnEditorActionListener(this);

    }



    /*
     * 初始化操作
     * */
    private void initView() {


        DaoSession daoSession = ((dbApp) mActivity.getApplicationContext()).getDaoSession();
        taskDao = daoSession.getTaskDao();
//        dataDao = daoSession.getMyDataDao();
        taskDetailsDao = daoSession.getTaskDetailsDao();
        taskDao = daoSession.getTaskDao();
        list = taskDao.loadAll();

        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new TaskMyAdapter(taskList, mActivity, this);
        mBinding.recyclerView.setAdapter(adapter);


        LiveEventBus.get().with("Name", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {

                count = s;

            }
        });

        //每个条目的点击事件
        adapter.setOnClickListener(new TaskMyAdapter.OnCliekListener() {
            @Override
            public void setItemOnClickListener(int position) {

                Bundle bundle = new Bundle();
                bundle.putString("taskID", taskList.get(position).getTask_ID());

                bundle.putString("count", count);

                //

                LiveEventBus.get().with("abc").post("Hello EventBus");

                //sql
                //UPDATE user
                //SET age = 25
                //WHERE username = 'John';
                String id = taskList.get(position).getTask_ID();


                if (taskList.get(position).getTask_state().equals("未盘点")) {
                    String sql = "update " + updaoSession.getTaskDao().getTablename() + " set " + TaskDao.Properties.Inventory_time.columnName + "=" +
                            "'" + getSystemTime() + "'" + " where "
                            + TaskDao.Properties.Task_ID.columnName + "='" + id + "'";
                    updaoSession.getDatabase().execSQL(sql);

                }

                boolean flag = true;
                LiveEventBus.get().with("setImage").post(flag);
                Navigation.findNavController(mActivity, R.id.fragment_my).navigate(R.id.inventoryDetailsFragment, bundle);


            }
        });

        //每个条目的长按事件
        adapter.setItemLongClickListener(new InventoryAdapter.ItemOnLongClickListener() {
            @Override
            public void ItemLongClickListener(int position) {

                AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
                        .setTitle("确定要删除：" + taskList.get(position).getTask_ID() + "吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String id = taskList.get(position).getTask_ID();

                                //DELETE FROM 表名 WHERE 条件;
                                String sql = "DELETE FROM " +
                                        updaoSession.getTaskDao().getTablename() +
                                        " WHERE " +
                                        TaskDao.Properties.Task_ID.columnName +
                                        " = " +
                                        '"' + id + '"';

                                updaoSession.getDatabase().execSQL(sql);

                                String sql1 = "DELETE FROM " +
                                        updaoSession.getTaskDetailsDao().getTablename() +
                                        " WHERE " +
                                        TaskDetailsDao.Properties.TaskID.columnName +
                                        " = " +
                                        '"' + id + '"';

                                updaoSession.getDatabase().execSQL(sql1);


                                taskList.remove(position);
                                adapter.notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .show();


            }
        });


//        MyDatabaseHelper dbHelper = new MyDatabaseHelper(mActivity);
//        SQLiteDatabase database = dbHelper.getWritableDatabase();

//        sharedPreferences = mActivity.getApplication().getSharedPreferences("data", MODE_PRIVATE);

        titleText = mActivity.findViewById(R.id.title_text);

        titleAdd = mActivity.findViewById(R.id.title_add);
//        titleTextBack = mActivity.findViewById(R.id.title_text_back);
        titleBack = mActivity.findViewById(R.id.title_back);

        titleAdd.setVisibility(View.VISIBLE);
        titleBack.setVisibility(View.VISIBLE);
        titleText.setText("盘点计划");

    }


    /*
     * 点击事件
     * */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                Navigation.findNavController(mActivity, R.id.fragment_my).navigateUp();
                break;
            case R.id.title_add:

                openFile();
                break;
            default:
                break;
        }
    }

    /**
     * 打开文件管理器
     */
    private void openFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //设置打开文件类型为.xls, .xlsx, .xlsx
        String[] mimeTypes = {"application/vnd.ms-excel", "application/x-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};
        intent.setType("application/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
//                //设置类型，任意类型
//                intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_EXTERNAL_STORAGE);

    }

    /*
     * 获取权限的方法
     * */
    private void getPermission() {

        if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 没有权限，请求权限
            ActivityCompat.requestPermissions(mActivity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                    1);
        } else {
            // 已经拥有权限
            // 在此处执行需要读写外部存储器权限的操作
            // 例如写入数据到文件，读取相册中的图片等
        }

    }

    /**
     * 跳转返回事件
     */
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        try {
            if (resultCode == Activity.RESULT_OK) {
                Uri uri = data.getData();

                progressDialog = new ProgressDialog(mActivity);
                progressDialog.setTitle("加载任务表");
                progressDialog.setMessage("正在加载ing...  " /*+ integer + "/" + 10000*/);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setCancelable(false); // 禁止用户通过返回键关闭对话框
                progressDialog.show();

                int start = uri.getPath().lastIndexOf(":");
                int end = uri.getPath().lastIndexOf(".");
                if (start != -1 && end != -1) {
                    fileName = uri.getPath().substring(start + 1, end);
                    filePath = uri.getPath().substring(start + 1);
                } else {
                    fileName = "null";
                    filePath = "null";
                }
                String file = Environment.getExternalStorageDirectory().getAbsolutePath();

                LiveEventBus.get().with("Name").post(fileName);
                List<Task> tlist = taskDao.queryBuilder().where(TaskDao.Properties.Task_ID.eq(fileName)).list();
                if (tlist.isEmpty()) {

                    datalist = null;

                    ThreadPool.runThread(() -> {
                            try {
                                datalist = ExcelUtils.readExcel(new String[]{"物品编码", "物资名称", "使用单位", "规格", "类型", "保管人", "入库时间", "存放地方", "打印编码", "备注", "备注2", "备注3"}, filePath, fileName, mActivity.getApplication());
                            }catch (Exception e) {
                                progressDialog.dismiss();
                                Log.d("InventoryPanFragment-----", e.getMessage());

                                mActivity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(mActivity, "对不起，您导入的表格有误", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                return;

                            }

                            progressDialog.dismiss();

                            Task task = new Task(null,
                                    fileName,
                                    "" + ExcelUtils.getSize(),
                                    "未盘点",
                                    getSystemTime(),
                                    "",
                                    fileName);
                            taskDao.insert(task);
                            mActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    refresh();
                                }
                            });

                    });

                } else {
                    Toast.makeText(mActivity, "文件已存在", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }


            }
        }catch (Exception e) {
            Toast.makeText(mActivity, "对不起，导入的Excl表格格式有误", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }


    }

    private void refresh() {
        list = taskDao.loadAll();
//        if (list.isEmpty()) {
//            mBinding.recyclerView.setVisibility(View.GONE);
//        } else {
//            mBinding.recyclerView.setVisibility(View.VISIBLE);
//        }
        //清空数据，防止重复
        if (!taskList.isEmpty()) {
            taskList.clear();
        }
        taskList.addAll(list);
        adapter.setData(taskList);

        //清空dao的缓存，因为greendao的缓存机制，是会从缓存中提取数据，所以更新后界面没有更新，但是数据库更新了
        taskDao.detachAll();
    }


    public void onRefresh() {
        refresh();
    }

    @Override
    public void onResume() {
        super.onResume();

        onRefresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }


    public String getSystemTime() {
        // 创建一个表示当前时间的 Date 对象
        Date currentDate = new Date();

        // 创建日期时间格式化对象，指定格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 将日期对象格式化为字符串
        String currentTime = dateFormat.format(currentDate);
        return currentTime;
    }


    @Override
    public boolean onEditorAction(TextView textView, int code, KeyEvent keyEvent) {
        if (code == EditorInfo.IME_ACTION_DONE ||
                (keyEvent != null && keyEvent.getKeyCode() == keyEvent.KEYCODE_ENTER)) {

//            list = taskDao.loadAll();
            hideKeyboard();
            taskList.clear();
            for (int i = 0; i < list.size(); i++) {

                if (list.get(i).getTask_ID().contains(mBinding.edtSearch.getText().toString())) {
                    taskList.add(list.get(i));
                }
                adapter.setData(taskList);
//                mBinding.edtSearch.setText("");
            }


            mBinding.edtSearch.setText("");
            return true;

        }

        return false;
    }


    private void hideKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) mActivity.getSystemService(INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.hideSoftInputFromWindow(mBinding.edtSearch.getWindowToken(), 0);
        }

        Consumer<String> con = (x) -> System.out.println(x);

        PrintStream ps = System.out;
        Consumer<String> con1 = ps::println;
    }
}